// pages/hot-goods/hot-goods.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 要获取的商品数据类型
    type: 1,
    // 总条数
    allCount: 0,
    // 总页数
    allPage: 1,
    // 开始页数
    page: 1,
    // 请求的条数
    size: 8,
    // 是否还有更多
    showTips: 1,
    // 控制加载
    loading: 0,
    // 加载图标的大小
    sysHeight: 0,
    // 商品数据列表
    goodsList: []
  },
  onLoad: function (options) {
    // 获取设备信息
    let info = wx.getSystemInfoSync();
    let sysHeight = info.windowHeight - 100;
    this.setData({
      sysHeight: sysHeight,
    });
  },
  onShow: function () {
    this.setData({
      goodsList: [],
      showTips: 1,
      allPage: 1,
      allCount: 0,
      page: 1,
      size: 8
    });
    this.getGoodList();
  },
  // 获取商品列表
  getGoodList() {
    let that = this;
    util.requestApi(api.getTypeProduct, {
      page: that.data.page,
      size: that.data.size,
      type: that.data.type
    }).then(function (res) {
      if (res.code == 200) {
        let goodsList = that.data.goodsList;
        that.setData({
          goodsList: goodsList.concat(res.content.data),
          allCount: res.content.count,
          allPage: Math.ceil(res.content.count / that.data.size),
          showTips: res.content.data.length < that.data.size ? 0 : 1,
          loading: 1
        })
      }
      that.getCartNum();
    })
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.setData({
      loading: 0,
      goodsList: [],
      showTips: 1,
      allCount: 0,
      allPage: 0,
      page: 1,
      size: 8,
    });
    this.getGoodList()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onReachBottom: function () {
    let that = this;
    if (that.data.page >= that.data.allPage) {
      that.setData({
        showTips: 0
      });
      return false;
    }
    that.setData({
      page: that.data.page + 1
    });
    that.getGoodList();
  },
  onShareAppMessage: function () {},
  // 获取购物车数量
  getCartNum: function () {
    let userID = wx.getStorageSync('userID')
    if (userID !== '' && userID !== undefined) {
      util.requestApi(api.getUserCartCount, {
        userID: userID
      }).then(function (res) {
        if (res.code === 200) {
          let cartGoodsCount = '';
          cartGoodsCount = res.content + '';
          wx.setTabBarBadge({
            index: 3,
            text: cartGoodsCount
          })
        } else {
          wx.removeTabBarBadge({
            index: 3,
          })
        }
      });
    }
  },
})